package com.shengyin.ec.controller.goods;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.shengyin.ec.exception.ControllerException;
import com.shengyin.ec.model.entity.ClusterCompany;
import com.shengyin.ec.model.entity.Company;
import com.shengyin.ec.model.entity.Goods;
import com.shengyin.ec.model.entity.GoodsType;
import com.shengyin.ec.service.alliance.AllianceService;
import com.shengyin.ec.service.goods.GoodsSearchService;
import com.shengyin.ec.service.goods.GoodsService;
import com.shengyin.ec.service.goods.GoodsTypeService;
import com.shengyin.ec.util.GetFirstLetterUtils;
import com.shengyin.ec.util.UploadFileUtil;

@Controller
public class GoodsController {

	@Autowired
	GoodsTypeService goodsTypeService;
	
	@Autowired
	GoodsService goodsService;
	
	@Autowired
	AllianceService allianceService;
	
  @Autowired
	GoodsSearchService goodsSearchService;

	@RequestMapping(value = "/toGoodsList.do")
	public String toGoodsList(Model model, HttpServletRequest request)
			throws IOException {

		int offset = 0;
		try {
			offset = Integer.valueOf(request.getParameter("pager.offset"));
			System.out.println("offset:" + offset);
		} catch (Exception ex) {
		}
		ArrayList<Goods> goodsList = (ArrayList<Goods>) goodsService
				.getGoodsList(offset, 10);//默认10条才进行分页
		Long maxSize=goodsService.getTotal();
		model.addAttribute("goodsList", goodsList);
		model.addAttribute("maxSize", maxSize);
		return "/admin/goods/goods";
	}
	
	@RequestMapping("/toGoodsSearch.do")
	public String toGoodsSearch(Model model, HttpServletRequest request)
			throws IOException {
		return "/admin/goods/search";
	}
	@RequestMapping("/goodsSearch.do")
	public String goodsSearch(Model model, HttpServletRequest request)
			throws IOException {
		String keyword = request.getParameter("keyword");
		System.out.println("keyword:"+keyword);
		List<Goods> goodsList = goodsSearchService.search(keyword, 0, 5);
		model.addAttribute("goodsList", goodsList);
		System.out.println(goodsList.size());
		return "/admin/goods/searchResult";
	}
	/*@RequestMapping(value="/toGoodsList.do")
	public String toGoodsList(Model model) throws Exception{
		
		List<Goods> goodsList = goodsService.getAllGoodsList();
		if(goodsList==null)
		{
			throw new Exception("商品不存在");
		}
	     model.addAttribute("goodsList",goodsList);
		
		return "/admin/goods/goods";
	}
	*/
	
	@RequestMapping(value="/toGoodsAdd.do")
	public String  toGoodsAdd(Model model,HttpServletRequest request) throws IOException{
		
		  ArrayList<GoodsType> typeList =(ArrayList<GoodsType>) goodsTypeService.getGoodsTypeList(0, 100);
	      model.addAttribute("typeList", typeList);	      
		  return "/admin/goods/goodsAdd";
	}
	
	@RequestMapping(value="/toModifyGoods.do")
	public String toGoodsModify(Model model,@RequestParam("id") int id){
		Goods goods = goodsService.getGoodsById(id);
		System.out.println(goods.getProductPicture()+"==========");
		ArrayList<GoodsType> typeList =(ArrayList<GoodsType>) goodsTypeService.getGoodsTypeList(0, 100);

        model.addAttribute("typeList", typeList);
		model.addAttribute("goods",goods);
		return "/admin/goods/goodsModify";
	}
	
	/**
	 * 商品添加
	 * */
	@RequestMapping(value="/goodsAdd.do",method = RequestMethod.POST)
	public String createGoods(GoodsForm goodsForm,HttpServletRequest request,@RequestParam("filename1")MultipartFile filename1) throws IOException, ControllerException{
		
		try {
			Goods goods=new Goods();
			
			BeanUtils.copyProperties(goods, goodsForm);
			String filePath =UploadFileUtil.Upload(request, filename1,"/圣茵/goods");
			goods.setProductPicture(filePath);
			String createTime=DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
			goods.setCreateDate(createTime);
			goods.setUpdateTime(createTime);
			String productCode = GetFirstLetterUtils.getUpcase(goods.getProductType())+Goods.getProductID();
			goods.setProductCode(productCode);
			goodsService.createGoods(goods);
			
			return "redirect:/toGoodsList.do";
		} catch (IllegalAccessException e) {
			e.printStackTrace();
			throw new ControllerException("参数不正确");
		} catch (InvocationTargetException e) {
			e.printStackTrace();
			throw new ControllerException("参数不正确");
		}
	}
	
	@RequestMapping("/deleteGoods.do")
	public String deletGoods(@RequestParam("id") long id){
		goodsService.removeGoodsByID(id);
		return "redirect:/toGoodsList.do";
	}
	
	@RequestMapping("/deleteSelectedGoods.do")
	public String deleteSelectedGoods(HttpServletRequest request){
		String [] ids=request.getParameterValues("ids");
		goodsService.deleteSelectedGoods(ids);
		return "redirect:/toGoodsList.do";
	}
	
	@RequestMapping("/modifyGoods.do")
	public String modifyGoods(GoodsForm goodsForm,HttpServletRequest request,@RequestParam("filename1")MultipartFile filename1) throws ControllerException{
		Goods  goods = new Goods();
		try {
			String specifications = goodsForm.getSpecifications();
			String description = goodsForm.getDescription();
			int commond = goodsForm.getIsCommond();
			int newGood = goodsForm.getIsNew();
			int promotion = goodsForm.getIsPromotion();
			int visible = goodsForm.getIsVisible();
			BeanUtils.copyProperties(goods, goodsForm);
			
			goods.setSpecifications(specifications);
			goods.setDescription(description);
			goods.setIsCommond(commond);
			goods.setIsNew(newGood);
			goods.setIsPromotion(promotion);
			goods.setIsVisible(visible);
			
			if(filename1.getSize()!=0)
			{
				String filePath =UploadFileUtil.Upload(request, filename1,"/圣茵/goods");
				goods.setProductPicture(filePath);
			}
			
			String updateTime=DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
			goods.setUpdateTime(updateTime);
			goodsService.modifyGoods(goods);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
			throw new ControllerException("参数不正确");
			
		} catch (InvocationTargetException e) {
			e.printStackTrace();
			throw new ControllerException("参数不正确");
		}
		return "redirect:/toGoodsList.do";
	}
	
	
	@RequestMapping("/toCategoryList.do")
	public String toCategory(Model model,@RequestParam("id") long id){
		GoodsType goodsType = goodsTypeService.getGoodsTypeById(id);
		List<Goods> goodsList =goodsService.getGoodsListByType(goodsType.getTypeName(), 0, 100);
		List<GoodsType> goodTypeList = goodsTypeService.getGoodsTypeList(0, 100);
		model.addAttribute("goodTypeList", goodTypeList);
		model.addAttribute("goodsList", goodsList);

		return "view/goods/category";
	}
	
	@RequestMapping("/viewProduct.do")
	public String ViewProduct(Model model,@RequestParam("id") long id){
		Goods goods =goodsService.getGoodsById(id);
		List<GoodsType> goodTypeList =goodsTypeService.getGoodsTypeList(0, 100);
		model.addAttribute("goods", goods);
		model.addAttribute("goodTypeList", goodTypeList);
		return "/view/goods/goodsDetail";
	}

	@RequestMapping("/changeImage.do")
	public String changeImage(Model model,HttpServletRequest request){
		List<Goods> goodsList = goodsService.getAllGoodsList();
		for(Goods goods : goodsList){
			String image = goods.getProductPicture();
			if(image!=null&&image.contains(".")){
				// 取得文件名后缀
				String ext = image.substring(image.lastIndexOf('.')).toLowerCase();
						
				String uuid = UUID.randomUUID().toString();
				String url = image.substring(0,image.lastIndexOf("/")+1)+uuid+ext;
				String sourcePath = request.getSession().getServletContext().getRealPath(image);
				String targetPath = request.getSession().getServletContext().getRealPath(url);
				File sourceFile = new File(sourcePath);
				File targetFile = new File(targetPath);
				if(sourceFile.exists()&&!sourceFile.isDirectory()){
					goodsService.changeImage(goods.getId(), url);
					sourceFile.renameTo(targetFile);
				}
			}
		}
		return "redirect:/toIndex.do";
	}

	
	
	@RequestMapping(value="searchGoods.do")
	public String searchGoods(HttpServletRequest request,Model model){
		
		int type=Integer.parseInt(request.getParameter("type"));
		String keyword = request.getParameter("keyword");
		keyword='%'+keyword+'%';
		if(type==0)
			return "redirect:/toGoodsList.do";
		List<Goods> goodsList = goodsService.getGoodsListByCondition(type,keyword,0,10);
		long maxSize = goodsService.getGoodsListByCondition(type,keyword).size();
		
		model.addAttribute("goodsList",goodsList);
		model.addAttribute("maxSize",maxSize);
		
		return "/admin/goods/goods";
		
	}
	
	@ExceptionHandler({ControllerException.class})  
	   public String exception(ControllerException e,HttpServletRequest request) {  
	       System.out.println(e.getMessage());  
	       request.setAttribute("error", e.getMessage());
	        return "/admin/error/error";  
	    }  
	//add by wql 2012-3-25
	
	@RequestMapping(value ="checkGoodNameExist.do", method = RequestMethod.GET)
	@ResponseBody
	public ModelMap checkGoodNameExist(Model model, @RequestParam("productName") String productName) {
  		boolean isExist;
		 ModelMap modelMap = new ModelMap();
		List<Goods> list = goodsService.checkGoodNameExist(productName.trim());
		if(list.size() == 0)
			isExist = true;
		else
			isExist = false;
		modelMap.addAttribute("isExist", isExist);
		return modelMap;
	}

}
